/*
Create all the context menu items.
*/
browser.contextMenus.create({
  id: "clnu-link-context-n",
  title: browser.i18n.getMessage("contextMenuItemOnLink"),
  contexts: ["link"],
});

function createContextMenuItemOnTab(info) {
  var mainversn = parseInt(info.version.split(".", 1)[0]);
  var onwhat = "tab";
  if (mainversn < 53) {
    onwhat = "all";
  }

  browser.contextMenus.create({
    id: "clnu-tab-context-n",
    title: browser.i18n.getMessage("contextMenuItemOnTab"),
    contexts: [onwhat],
  });
}
browser.runtime.getBrowserInfo().then(createContextMenuItemOnTab);

function CopyOnLink(info) {
  CopyLinkNameandurlToClipboard({url:info.linkUrl,title:info.linkText});
}
function CopyOnTab(tab) {
  CopyLinkNameandurlToClipboard({url:tab.url,title:tab.title});
}

/*
The click event listener, where we perform the appropriate action given the
ID of the menu item that was clicked.
*/
browser.contextMenus.onClicked.addListener(function (info, tab) {
  switch (info.menuItemId) {
    case "clnu-link-context-n":
      CopyOnLink(info);
      break;
    case "clnu-tab-context-n":
      CopyOnTab(tab);
      break;
  }
});

async function CopyLinkNameandurlToClipboard(link) {
  console.log(link);
  let text = (await browser.storage.local.get('format')).format || '[%T](%U)';
  text = text.replace('%U',link.url).replace('%T',link.title);
  let html = `<a href="${link.url}">${link.title}</a>`;
  const item = new ClipboardItem({
    "text/html": new Blob([html], { type: "text/html" }),
    "text/plain": new Blob([text], { type: "text/plain" }),
  });
  try {
    await navigator.clipboard.write([item]);
  } catch (err) {
    document.addEventListener("copy", oncopy, true);
    let res = document.execCommand("copy") ? "success" : "fail";
    console.log("navigator.clipboard.write: fail.  document.execCommand: "+res);
  }
  function oncopy(event) {
    document.removeEventListener("copy", oncopy, true);
    // Hide the event from the page to prevent tampering.
    event.stopImmediatePropagation();
    // Overwrite the clipboard content.
    event.preventDefault();
    event.clipboardData.setData("text/html", html);
  }
}